package com.hexus.eve.actions;

import java.util.List;
import java.util.ResourceBundle;

import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.transaction.annotation.Transactional;

import com.hexus.eve.entities.Account;
import com.hexus.eve.entities.CharacterBlueprint;
import com.hexus.eve.entities.security.User;
import com.hexus.eve.utils.CurrentUser;
import com.opensymphony.xwork2.ActionSupport;
import com.hexus.eve.entities.Character;

public class DeleteAccount extends ActionSupport{
	private static final long serialVersionUID = 1L;

	@Autowired
	private SessionFactory sessionFactory;
	
	private Integer id = -1;
	private Boolean delete = false;
	
	public String execute() {
		
		HibernateTemplate ht = new HibernateTemplate(sessionFactory);
		User user = CurrentUser.getUser();
		
		if(id != -1) {
			List<Account> accounts = user.getAccounts();
	
			for(Account a: accounts) {
				if(a.getId().intValue() == id) {
					
					for(Character c : a.getCharacters()) {
						//ht.deleteAll(c.getBlueprints());
						for(CharacterBlueprint cb : c.getBlueprints()) {
							ht.delete(cb);
						}
						c.getBlueprints().clear();
					}
					ht.delete(a);
					accounts.remove(a);
					delete = true;
					return SUCCESS;
				}
			}
			ResourceBundle bundle = ResourceBundle.getBundle ("global", getLocale());
			addActionError(bundle.getString("validation.cant.find.record"));
		}
		
		return SUCCESS;
	}

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public Boolean getDelete() {
		return delete;
	}

	public void setDelete(Boolean delete) {
		this.delete = delete;
	}
}
